const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
var cors = require('koa2-cors');
const mongoose = require('mongoose')
const { connect, initSchemas } = require('./database/index.js')
//getpath.js
const multer = require('koa-multer')
const path = require('path')
const qiniu = require("qiniu");
const index = require('./appApi/index.js')
const detail = require('./appApi/detail.js')
const admin = require('./appApi/backAdmin.js')

const app = new (Koa)
const router = new (Router)
app.use(bodyParser())
app.use(cors());

; (async () => {
    await connect()
    initSchemas()
})()
//服务器测试接口
router.get('/',(ctx)=>{
    ctx.body = "邹智敏的服务器"
})

// 配置
// var storage = multer.diskStorage({
//     //文件保存路径
//     destination: function (req, file, cb) {
//         cb(null, 'public/phoneManageSystem/')//path.resolve('public/phoneManageSystem')
//     },
//     //修改文件名称
//     filename: function (req, file, cb) {
//         var fileFormat = (file.originalname).split(".");  //以点分割成数组，数组的最后一项就是后缀名
//         cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
//     }
// })
// //加载配置
// var upload = multer({
//      storage: storage,
//      limits: {
//         fileSize: 1024*1024/2 // 限制512KB
//       }
// });
//获取七牛的token
router.get("/getuploadtoken", async (ctx, next) => {
    const accessKey = 'jAfLbT32O3oNb78-wG6t-ztA4d_VBrUAt7QUBtZn';   //秘钥管理中的AK
    const secretKey = 'By8WeNPW3jJvJfDAgfSz75Z3paCTGhUjcAJaiFQX';    //秘钥管理中的SK
    const bucket = "hellsink";     //创建的存储空间文件夹名字
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    const options = {
        scope: bucket,
        expires: 3600 * 24,    //过期时间
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
    ctx.body = uploadToken;   //当前端请求获得token的时候，就把生成的token返回给前端
})

router.use('/index',index.routes())
router.use('/detail',detail.routes())
router.use('/admin',admin.routes())
app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000,()=>{
    console.log('Mr.zou 你的服务器在3000端口开启了！！！');
})
